package com.ricchieri.task;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.ricchieri.common.EmailSender;
import com.ricchieri.model.EmailToSend;
import com.ricchieri.service.interf.IEmailToSendService;

@Service
public class SendEmailTask {
	
	IEmailToSendService emailToSend;
	
    @Scheduled(fixedRate = 60000)
    public void sendMail() {
    	List<EmailToSend> emailToSendList = emailToSend.getAllEmailToSend();
    	EmailSender emailSender = new EmailSender();
    	Boolean result;
    	
    	for (EmailToSend emailToS : emailToSendList) {
    		result = emailSender.sendEmail(emailToS);
    		
    		emailToS.setIsMessageSent(result);
    		emailToS.setAttemptCounter(emailToS.getAttemptCounter() + 1);
    		emailToS.setSendDate(new Date(System.currentTimeMillis()));
    		
    		emailToSend.update(emailToS);
		}
    }

	public IEmailToSendService getEmailToSend() {
		return emailToSend;
	}

	@Autowired
	public void setEmailToSend(IEmailToSendService emailToSend) {
		this.emailToSend = emailToSend;
	}
 
    
}
